package com.tbit.uqbike.service.business.impl;

import com.tbit.uqbike.constant.MachineFunctionConstant;
import com.tbit.uqbike.constant.enums.MachineFunctionModeEnum;
import com.tbit.uqbike.object.pojo.Camera;
import com.tbit.uqbike.object.pojo.Machine;
import com.tbit.uqbike.object.pojo.MachineFunction;
import com.tbit.uqbike.object.pojo.vo.BatchOperationMsgVO;
import com.tbit.uqbike.service.business.MachineFunctionService;
import com.tbit.uqbike.webmanager.business.machine_op_log.service.MachineOpLogService;
import com.tbit.uqbike.webmanager.dao.core.MachineDao;
import com.tbit.uqbike.webmanager.dao.core.MachineFunctionDao;
import com.tbit.uqbike.webmanager.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.tbit.uqbike.constant.MachineFunctionConstant.FUNCTION_NAME_MAP;

/**
 * @Author: chen
 * @Description: 设备功能绑定
 * @Date: 创建于 17:43 2020/6/2
 */
@Service
public class MachineFunctionServiceImpl implements MachineFunctionService {
    @Autowired
    private MachineFunctionDao machineFunctionDao;
    @Autowired
    private MachineDao machineDao;
    @Autowired
    private MachineOpLogService machineOpLogService;

    @Override
    public List<MachineFunction> queryPage(Integer accountId, String machineNO, Integer functionType, Integer pageNO,
                                           Integer rowCount) {
        Map<String, Object> map = new HashMap<>();
        map.put("accountId", accountId);
        map.put("machineNO", machineNO);
        map.put("functionType", functionType);
        map.put("pageNO", (pageNO - 1) * rowCount);
        map.put("rowCount", rowCount);
        return machineFunctionDao.queryPage(map);
    }

    @Override
    public Integer queryCount(Integer accountId, String machineNO, Integer functionType) {
        Map<String, Object> map = new HashMap<>();
        map.put("accountId", accountId);
        map.put("machineNO", machineNO);
        map.put("functionType", functionType);
        return machineFunctionDao.queryCount(map);
    }

    @Override
    public BatchOperationMsgVO<String> addBatch(List<String> list, Integer functionType, String functionName,
                                                Integer functionValue,Integer functionMode) {
        BatchOperationMsgVO<String> batchOperationMsgVO = new BatchOperationMsgVO<>();
        List<String> isBoundList = new ArrayList<>();
        List<String> successList = new ArrayList<>();
        List<String> notExistNO = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("machineNOs", StringUtil.getArrayListString(list));
        List<Machine> machines = machineDao.getByMachineNOs(map);
        Map<Integer, String> machineNoMap = new HashMap<>();
        machines.forEach(machine -> machineNoMap.put(machine.getMachineId(), machine.getMachineNO()));
        /**设备表存在编号*/
        List<String> existNO = new ArrayList<>();
        /**设备表存在的id*/
        List<Integer> existID = new ArrayList<>();
        /**批量添加的id*/
        List<Integer> addID = new ArrayList<>();
        if (machines.size() > 0) {
            Map<Integer, Machine> machineMap = new HashMap<>();
            /**组装数据*/
            for (Machine machine : machines) {
                machineMap.put(machine.getMachineId(), machine);
                existNO.add(machine.getMachineNO());
                existID.add(machine.getMachineId());
            }
            /**查询存在设备和输入的不一致*/
            if (list.size() > existNO.size()) {
                for (String machineNO : list) {
                    if (!existNO.contains(machineNO)) {
                        notExistNO.add(machineNO);
                    }
                }
            }
            /**查询是否存在绑定设备*/
            List<Integer> existBoundId = getByMachineIds(existID, functionType);
            if (existBoundId.size() > 0) {
                for (Integer machineId : existID) {
                    if (!existBoundId.contains(machineId)) {
                        addID.add(machineId);
                    } else {
                        //存在绑定设备
                        isBoundList.add(machineNoMap.get(machineId));
                    }
                }
            } else {
                addID.addAll(existID);
            }
            /**入库*/
            if (addID.size() > 0) {
                List<MachineFunction> functions = new ArrayList<>();
                List<Camera> cameraList = new ArrayList<>();
                Date updateTime = new Date();
                /**组装需要添加的数据*/
                for (Integer machineId : addID) {
                    successList.add(machineNoMap.get(machineId));
                    MachineFunction machineFunction = new MachineFunction();
                    machineFunction.setFunctionName(functionName);
                    machineFunction.setFunctionType(functionType);
                    machineFunction.setFunctionValue(functionValue);
                    machineFunction.setMachineId(machineId);
                    machineFunction.setFunctionMode(functionMode);
                    machineFunction.setUpdateTime(updateTime);
                    functions.add(machineFunction);
                    //判断是否是开启文明骑行的
                    if (functionType != null && Objects.equals(MachineFunctionConstant.MACHINE_TYPE_RULE_RIDE, functionType) && functionValue != null && functionValue == 1) {
                        Machine machine = machineMap.get(machineId);
                        if (machine != null) {
                            cameraList.add(new Camera(machine.getAccountId(), machine.getMachineNO(), null, updateTime));
                        }
                    }
                }
                machineFunctionDao.addBatch(functions);

                if (cameraList.size() > 0) {
                    machineFunctionDao.addCameraBatch(cameraList);
                }

                // 添加车辆操作日志
                String operation = "功能配置-" + FUNCTION_NAME_MAP.get(functionType);
                String detail = null;
                if (functionType != null && functionType.equals(MachineFunctionConstant.PHOTO_RETURN_CAR)) {
                    detail = "模型：" + Arrays.stream(MachineFunctionModeEnum.values())
                            .filter(e -> e.getModeCode().equals(functionMode))
                            .map(MachineFunctionModeEnum::getModeName)
                            .findFirst()
                            .orElse("未知模型");
                }
                List<Machine> addMachines = machines.stream()
                                .filter(m -> addID.contains(m.getMachineId()))
                                .collect(Collectors.toList());
                machineOpLogService.batchAddRecord(operation, "添加", true, detail, addMachines);
            }
        } else {
            notExistNO.addAll(list);
        }
        //不存在的设备编号
        batchOperationMsgVO.setFailList(notExistNO)
                //已绑定的设备编号
                .setAbnormalList(isBoundList)
                //成功的设备编号
                .setSuccessList(successList);
        return batchOperationMsgVO;
    }

    @Override
    public BatchOperationMsgVO<String> delBatch(List<String> list, Integer functionType) {
        BatchOperationMsgVO<String> batchOperationMsgVO = new BatchOperationMsgVO<>();
        List<String> abnormalList = new ArrayList<>();
        List<String> failList = new ArrayList<>();
        List<String> notExistNO = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("machineNOs", StringUtil.getArrayListString(list));
        List<Machine> machines = machineDao.getByMachineNOs(map);
        /**设备表存在编号*/
        List<String> existNO = new ArrayList<>();
        /**设备表存在的id*/
        List<Integer> existID = new ArrayList<>();
        if (machines.size() > 0) {
            List<String> cameraMachineNoList = new ArrayList<>();
            /**组装数据*/
            for (Machine machine : machines) {
                Map<String, Object> params = new HashMap<>();
                params.put("machineId", machine.getMachineId());
                params.put("functionType", functionType);
                if (null == machineFunctionDao.getByMachineId(params)) {
                    notExistNO.add(machine.getMachineNO());
                    //不存在绑定关系的设备编号
                    abnormalList.add(machine.getMachineNO());
                    continue;
                }
                existNO.add(machine.getMachineNO());
                existID.add(machine.getMachineId());
                if (Objects.equals(MachineFunctionConstant.MACHINE_TYPE_RULE_RIDE, functionType)) {
                    //删除文明骑行摄像头功能的
                    cameraMachineNoList.add(machine.getMachineNO());
                }

            }
            /**查询存在设备和输入的不一致*/
            if (list.size() > existNO.size()) {
                for (String machineNO : list) {
                    if (!existNO.contains(machineNO) && !notExistNO.contains(machineNO)) {
                        notExistNO.add(machineNO);
                        failList.add(machineNO);
                    }
                }
            }
            /**批量删除*/
            if (!existID.isEmpty()) {
                Map<String, Object> param = new HashMap<>();
                param.put("machineIds", StringUtil.getListString(existID));
                param.put("functionType", functionType);
                machineFunctionDao.delBatch(param);
            }
            //批量删除文明骑行摄像头功能
            if (cameraMachineNoList.size() > 0) {
                machineFunctionDao.deleteCameraBatch(cameraMachineNoList);
            }

            // 添加车辆操作日志
            String operation = "功能配置-" + FUNCTION_NAME_MAP.get(functionType);
            List<Machine> delMachines = machines.stream()
                            .filter(m -> existID.contains(m.getMachineId()))
                            .collect(Collectors.toList());
            machineOpLogService.batchAddRecord(operation, "删除", true, null, delMachines);
        } else {
            failList.addAll(list);
        }
        //不存在绑定关系的设备编号
        batchOperationMsgVO.setAbnormalList(abnormalList)
                //不存在的设备编号
                .setFailList(failList)
                //成功删除的设备编号
                .setSuccessList(existNO);
        machineFunctionDao.deleteNotExistHelmetBound();
        machineFunctionDao.deleteNotExistHelmetAbnormal();
        return batchOperationMsgVO;
    }

    @Override
    public List<Integer> getByMachineIds(List<Integer> list, Integer functionType) {
        Map<String, Object> map = new HashMap<>();
        map.put("machineIds", StringUtil.getListString(list));
        map.put("functionType", functionType);
        return machineFunctionDao.getByMachineIds(map);
    }

    @Override
    public List<MachineFunction> getByType(Integer accountId, Integer functionType) {
        Map<String, Object> map = new HashMap<>();
        map.put("accountId", accountId);
        map.put("functionType", functionType);
        return machineFunctionDao.getByType(map);
    }

    @Override
    public MachineFunction getByMachineId(Integer machineId, Integer functionType) {
        Map<String, Object> map = new HashMap<>();
        map.put("machineId", machineId);
        map.put("functionType", functionType);
        return machineFunctionDao.getByMachineId(map);
    }


}
